
#ifndef DOCUMENTBROWSER_H
#define DOCUMENTBROWSER_H

#include <BSet>
#include <BTree>
#include <BWidget>
#include <BImage>
#include <BSlider>
#include <BTextEdit>
#include <BRectArray>
#include <BPainter>

#include "SourceEdit.h"
#include "ScriptFormat.h"
#include "PromptBox.h"

class ScriptBrowser: public BTextEdit
{
	BOBJECT(ScriptBrowser)
private:
	struct Chunk
	{
		Chunk()
		{
			visible = true;
			begin = -1;
			end = -1;
		}
		bool		visible;
		int			begin;
		int			end;
		BRect		rect;
		BRect		head;
		BRect		tail;
	};
	typedef BTree<Chunk>	ChunkTree;

public:
	ScriptBrowser(BWidget* parent = 0);
	~ScriptBrowser();

protected:
	void freshDocument();
	void drawErrorFlag(BPainter& painter, SourceFormat::Item* item);

	void createChunk(ChunkTree::iterator& it, int& line);
	void freshChunk(ChunkTree::iterator& it);
	void foldedChunk(ChunkTree::iterator& it);
	ChunkTree::iterator chunkUnder(const BPoint& point);
	ChunkTree::iterator chunkUnder(ChunkTree::iterator& it, const BPoint& point);
	void drawChunk(BPainter& painter, ChunkTree::iterator& it);

protected:
	void slotAssetChanged(BObject* object, const BValue& value);
	void slotTextEditFlushed(BObject* object, const BValue& value);
	void slotScriptCompiled(BObject* object);

protected:
	virtual void updateEvent(const BEvent& event);

	virtual void showEvent(const BEvent& event);
	virtual void closeEvent(const BEvent& event);

	virtual void resizeEvent(const BEvent& event);

	virtual void styleEvent(const BEvent& event);
	virtual void freshEvent(const BEvent& event);
	virtual void paintEvent(const BEvent& event);

	virtual void mousePressEvent(const BMouseEvent& mouseEvent);
	virtual void mouseReleaseEvent(const BMouseEvent& mouseEvent);
	virtual void mouseMoveEvent(const BMouseEvent& mouseEvent);

private:
	BHolder<BScript>		_script;
	BRect					_breakArea;
	BSet<int>				_breakLines;
	BRect					_chunkArea;
	BTree<Chunk>			_chunkTree;
	ChunkTree::iterator		_hoveredChunk;
	ScriptFormat::Item*		_hoveredItem;
	BValue					_codeRectsValue;
};

#endif